package com.atguigu.spzx.product.service.Impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.product.Product;
import com.atguigu.spzx.model.entity.product.ProductDetails;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.h5.ProductSkuDto;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.ProductItemVo;
import com.atguigu.spzx.product.mapper.ProductDetailsMapper;
import com.atguigu.spzx.product.mapper.ProductMapper;
import com.atguigu.spzx.product.mapper.ProductSkuMapper;
import com.atguigu.spzx.product.service.ProductService2;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author syh
 * @create 2023-09-01 10:39
 */
@Service
public class ProductService2Impl implements ProductService2 {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailsMapper productDetailsMapper;
    @Resource
    ProductSkuMapper productSkuMapper;
    @Override
    public PageInfo<ProductSku> findByPage(Integer page, Integer limit, ProductSkuDto productSkuDto) {
        PageHelper.startPage(page,limit);
        List<ProductSku> list=productSkuMapper.findByPage(productSkuDto);
        return new PageInfo<ProductSku>(list);
    }

    @Override
    public ProductItemVo item(Long skuId) {
        Map<String, Object> map = new HashMap<>();

        //当前sku信息
        ProductSku productSku = productSkuMapper.getById(skuId);
        //当前商品信息
        Product product = productMapper.getById(productSku.getProductId());
        //同一个商品下面的sku信息列表
        List<ProductSku> productSkuList = productSkuMapper.findByProductId(productSku.getProductId());
        //建立sku规格与skuId对应关系
        Map<String,Object> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });

        //商品详情信息
        ProductDetails productDetails = productDetailsMapper.getByProductId(productSku.getProductId());

        ProductItemVo productItemVo = new ProductItemVo();
        productItemVo.setProductSku(productSku);
        productItemVo.setProduct(product);
        productItemVo.setDetailsImageUrlList(Arrays.asList(productDetails.getImageUrls().split(",")));
        productItemVo.setSliderUrlList(Arrays.asList(product.getSliderUrls().split(",")));
        productItemVo.setSpecValueList(JSON.parseArray(product.getSpecValue()));
        productItemVo.setSkuSpecValueMap(skuSpecValueMap);
        return productItemVo;
    }

    @Override
    public ProductSku getBySkuId(Long skuId) {
        return productSkuMapper.getById(skuId);
    }

    @Override
    public ProductSku findSkuBySkuId(Long skuId) {
        return productSkuMapper.getById(skuId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ProductSku> findProductSkus(List<OrderItem> orderItemList) {
        //可以加分布式锁+数据库字段值设置为无符号 解决超卖问题
        //不能加数据库锁：可能会锁升级或者死锁
        //1、如果orderItemList为空返回空
        if(CollectionUtils.isEmpty(orderItemList)){
            return null;
        }
        //2、根据orderItem集合 遍历 判断价格是否变动、判断库存是否足够  如果足够 更新库存
        List<Long> skuIds = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        List<ProductSku> productSkus = productSkuMapper.findSkusBySkuIds(skuIds);
        if(CollectionUtils.isEmpty(productSkus) || productSkus.size()!= orderItemList.size()){
            //查询商品列表 和订单项列表对应不上
            throw new GuiguException(ResultCodeEnum.UNKNOW_ERROR);
        }
        //3、验库存和价格
        //将productSku转为Map<SkuId , ProductSku>
        Map<Long, ProductSku> map = new HashMap<>();
        productSkus.forEach(productSku -> {
            map.put(productSku.getId() , productSku);
        });
        orderItemList.forEach(orderItem -> {
            //获取购物项对应的商品
            ProductSku productSku = map.get(orderItem.getSkuId());
            //判断库存
            if(productSku.getStockNum()<orderItem.getSkuNum()){
                throw new GuiguException(ResultCodeEnum.UNKNOW_ERROR);
            }
            //判断价格
            if(productSku.getSalePrice().compareTo(orderItem.getSkuPrice())!=0){
                throw new GuiguException(ResultCodeEnum.UNKNOW_ERROR);
            }
            //更新库存: 数据库product_sku表库存字段需要设置无符号约束
            boolean updateFlag = productSkuMapper
                    .updateStockNumById(productSku.getId() , orderItem.getSkuNum());
            if(!updateFlag){
                //商品减库存失败
                throw new GuiguException(ResultCodeEnum.UNKNOW_ERROR);
            }
        });

        return productSkus;
    }
}
